package thread;

/**
 * 线程并发安全问题
 */
public class SyncDemo {
    public static void main(String[] args) {
        Table table = new Table();
        Thread t1 = new Thread() {
            public void run() {
                while (true) {
                    int count = table.getBean();
                    Thread.yield();
                    System.out.println(getName() + ":" + count);
                }

            }
        };
        Thread t2 = new Thread() {
            public void run() {
                while (true) {
                    int count = table.getBean();
                    Thread.yield();
                    System.out.println(getName() + ":" + count);
                }
            }
        };

        t1.start();
        t2.start();
    }
}


class Table {
    private int bean = 20;
//    synchronized 同步方法
    public synchronized int getBean() {
        if (bean == 0) {
            throw new RuntimeException("没有豆子了");
        }
        Thread.yield();
        return bean--;
    }
}
